<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException ;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Http\Request;

class JWTAuthCheck
{

     /**
     * The JWT Authenticator.
     *
     * @var \Tymon\JWTAuth\JWTAuth
     */
    protected $auth;

    /**
     * Create a new BaseMiddleware instance.
     *
     * @param  \Tymon\JWTAuth\JWTAuth  $auth
     *
     * @return void
     */
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
    }


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (! $token = $this->auth->setRequest($request)->getToken()) {
            return response()->json(['code' => -400,'msg' => 'token_not_provided：token不存在','data' => '',]);
        }
        try {
            $user = $this->auth->authenticate($token);
        } catch (TokenExpiredException $e) {
             return response()->json(['code' => -401,'msg' => 'token_invalid Token无效','data' => '',]);
        } catch (TokenInvalidException $e) {
            return response()->json(['code' => -401,'msg' => 'token_invalid Token无效','data' => '',]);
        } catch (JWTException $e) {
             return response()->json(['code' => -401,'msg' => 'token_invalid Token无效','data' => '',]);
        }
        if (empty($user)) {
             return response()->json(['code' => -402,'msg' => '用户不存在','data' => '',]);
        }
        return $next($request);
    }
}
